﻿using System;
using System.Web.UI.WebControls;
using Yglu.BusinessLayer;
using Yglu.BusinessLayer.Entities;
using Yglu.BusinessLayer.Enums;

namespace Yglu.WebAdmin
{
	public partial class Orders_aspx : BasePage
	{
		#region Main methods

		protected void Page_Load(object sender, EventArgs e)
		{
			CheckPermissions(AdminLevel.Store);

			if (!IsPostBack)
			{
				PanDetails.Visible = false;

				SetDefaults();
				LoadData();
			}
		}

		protected void ButLoad_Click(Object sender, EventArgs e)
		{
			LoadData();
		}

		private void SetDefaults()
		{
			SetDefaults(GridOrders);

			TxtDateFrom.Text = DateTime.Now.AddDays(-1).ToString("d");
			TxtDateTo.Text = DateTime.Now.ToString("d");
		}

		private void LoadData()
		{
			Period period = new Period();

			period.DateFrom = Convert.ToDateTime(TxtDateFrom.Text + " 00:00:00");
			period.DateTo = Convert.ToDateTime(TxtDateTo.Text + " 23:59:59");

			if (SessionManager.LoggedStore.Id > 0)
			{
				GridOrders.DataSource = new OrderCollection(DataAccess.Order_Get(SessionManager.LoggedStore, period));
			}
			else
			{
				GridOrders.DataSource = new OrderCollection(DataAccess.Order_Get(period));
			}

			GridOrders.DataBind();

			PanDetails.Visible = false;
			PanGrid.Visible = true;
		}

		#endregion

		#region View order details

		protected void GridOrders_RowCommand(Object sender, GridViewCommandEventArgs e)
		{
			ViewOrder(Convert.ToInt32(e.CommandArgument));
		}

		protected void ButBack_Click(Object sender, EventArgs e)
		{
			PanDetails.Visible = false;
			PanGrid.Visible = true;
		}

		private void ViewOrder(Int32 row)
		{
			Int32 id = Convert.ToInt32(GridOrders.Rows[row].Cells[0].Text);
			Order o = new Order(id);

			LblOrderId.Text = o.Id.ToString();
			LblStoreTitle.Text = o.StoreTitle;
			LblTerminal.Text = o.Terminal.Id.ToString();
			LblDateOrdered.Text = o.DateOrdered.ToString("G");
			LblDatePaid.Text = o.DateOrdered.ToLongTimeString();
			LblUserFullName.Text = o.UserFullName;
			LblCustomer.Text = o.Customer;
			LblTotalPrice.Text = o.TotalPrice.ToString("0.00");
			LblDiscount.Text = o.Discount.ToString("0.00");
			LblPricePaid.Text = o.PriceWithDiscount.ToString("0.00");

			PanDetails.Visible = true;
			PanGrid.Visible = false;

			o.Combos = new ComboCollection(DataAccess.Combo_Get(o));

			foreach (Combo c in o.Combos)
			{
				c.Products = new ProductCollection(DataAccess.Product_Get(c));
			}

			ListCombos.DataSource = o.Combos;
			ListCombos.DataBind();
		}

		#endregion

	}
}